package mygw.jtthink.com.filters;

import io.jsonwebtoken.*;
import mygw.jtthink.com.Utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.net.URI;

@Component
public class TokenCheckGatewayFilterFactory extends AbstractGatewayFilterFactory {
    @Override
    public GatewayFilter apply(Object config) {
        return ((exchange, chain) -> {
            String token = exchange.getRequest().getQueryParams().getFirst("token");
            if (token == null || token.equals("")) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }else {
                try{
                    String getUserName=pareseToken(token);
                    ServerHttpRequest newRequest= exchange.getRequest().mutate()
                            .header("CURRENT_USER",getUserName).build();
                    return chain.filter(exchange.mutate().request(newRequest)
                            .build());
                }catch (Exception ex){

                    System.out.println(ex.getMessage());
                }
            }
            URI uri = URI.create("http://localhost/unauthorize");
            ServerHttpRequest errRequest = exchange.getRequest().mutate()
                    .path(uri.getRawPath()).build();

            Route currentRoute = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
            Route newRoute=Route.async()
                    .id(currentRoute.getId())
                    .asyncPredicate(currentRoute.getPredicate())
                    .uri(uri).build();
            exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR,newRoute);

            return chain.filter(exchange.mutate().request(errRequest).build());//依然跳转真实api
        });
    }
    @Autowired
    TokenUtil tokenUtil;
    private String pareseToken(String token) throws Exception{
        try{
            Claims claims = Jwts.parser()
                    .setSigningKey("123456")
                    .parseClaimsJws(token)
                    .getBody();
            String userName = claims.get("username").toString();
            if(!tokenUtil.isExistToken(userName,token,true)){
                throw new Exception("token expired");
            }
            return userName;
        }catch (ExpiredJwtException ex){
            throw new Exception("token expired");//过期
        }catch (SignatureException | MalformedJwtException e){
            throw new Exception("token error");
        }
    }
}
